package common;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: shenran
 * Date: 13-7-15
 * Time: 下午1:51
 * To change this template use File | Settings | File Templates.
 */
public class HttpRequestTask implements Runnable {
    private HttpMethod m_method;
    private String m_url;
    private int m_priority = 1;
    private int m_request_id;
    private HashMap<String, String> m_post_map;
    private HTTPResponseCallback m_callback;
    private Boolean isContinue = true;


    public void CreatHttpRequest(String url, HttpMethod method, HashMap<String, String> post_map, int request_id, HTTPResponseCallback callback) {
        m_url = url;
        m_method = method;
        m_post_map = post_map;
        m_request_id = request_id;
        m_callback = callback;
        HTTPTaskManager.getInstance().AppendTask(this);
    }

    @Override
    public void run() {
        //To change body of implemented methods use File | Settings | File Templates.
        switch (m_method) {
            case GET:
                RESPONSE_BY_GET();
                break;
            case POST:
                RESPONSE_BY_POST();
                break;
        }
        HTTPTaskManager.getInstance().didComplete(this);
    }

    private static final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            HttpConnectStatus status = HttpConnectStatus.values()[message.what];
            switch (status) {
                case DID_START: {
                    break;
                }
                case DID_SUCCEED: {
                    HTTPResponseCallback _Report = (HTTPResponseCallback) message.obj;
                    Object data = message.getData();
                    if (_Report != null) {
                        if (data != null) {
                            Bundle bundle = (Bundle) data;
                            byte[] result = bundle.getByteArray("callbackkey");
                            int RequestId = message.arg1;
                            _Report.SuccessCallBack(result, RequestId);
                        }
                    }
                    break;
                }
                case DID_ERROR: {
                    HTTPResponseCallback _Report = (HTTPResponseCallback) message.obj;
                    int RequestId = message.arg1;
                    _Report.ErrorCallBack(null, RequestId);
                    break;
                }
            }

        }
    };

    public void Cancel() {
        isContinue = false;
    }

    private void RESPONSE_BY_GET() {
        try {
            //使用HttpURLConnection打开连接
            URL url = new URL(m_url);
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            //设置输入和输出流
            urlConn.setDoOutput(true);
            urlConn.setDoInput(true);
            //设置请求方式为GET
            urlConn.setRequestMethod("GET");
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            InputStream inputStream = urlConn.getInputStream();

//            //使用循环来读取获得的数据
            while (isContinue) {
                //我们在每一行后面加上一个"\n"来换行
                byte[] buffer = new byte[1024];
                int size = inputStream.read(buffer);

                if (size > 0) {
                    outputStream.write(buffer, 0, size);
                } else {
                    break;
                }
            }
            //关闭InputStreamReader
            inputStream.close();
            //关闭http连接
            urlConn.disconnect();
            byte[] result = outputStream.toByteArray();
            outputStream.close();
            if (isContinue) {

                sendMessage(result, HttpConnectStatus.DID_SUCCEED);
            } else {
                sendMessage(result, HttpConnectStatus.DID_CANCEL);
            }

        } catch (ProtocolException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            sendMessage(null, HttpConnectStatus.DID_ERROR);
        } catch (MalformedURLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            sendMessage(null, HttpConnectStatus.DID_ERROR);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            sendMessage(null, HttpConnectStatus.DID_ERROR);
        }

    }


    private void RESPONSE_BY_POST() {
        HttpPost httpPost = new HttpPost(m_url);
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        if (m_post_map != null) {
            for (String key : m_post_map.keySet()) {

                String value = m_post_map.get(key);
                BasicNameValuePair valuesPair = new BasicNameValuePair(key, value);
                params.add(valuesPair);
            }
        }
        HttpEntity httpentity = null;
        try {
            httpentity = new UrlEncodedFormEntity(params, "UTF-8");
            httpPost.setEntity(httpentity);
            //取得默认的HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            //取得HttpResponse
            HttpResponse httpResponse = httpclient.execute(httpPost);
            httpResponse = httpclient.execute(httpPost);
            //HttpStatus.SC_OK表示连接成功
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //取得返回的字符串
                byte[] result = EntityUtils.toByteArray(httpResponse.getEntity());
                sendMessage(result, HttpConnectStatus.DID_SUCCEED);
            } else {
                sendMessage(null, HttpConnectStatus.DID_ERROR);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            sendMessage(null, HttpConnectStatus.DID_ERROR);
        } catch (ClientProtocolException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            sendMessage(null, HttpConnectStatus.DID_ERROR);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            sendMessage(null, HttpConnectStatus.DID_ERROR);
        }


    }

    private void sendMessage(byte[] result, HttpConnectStatus status) {

        Message message = Message.obtain(handler, status.ordinal(),
                m_callback);
        message.arg1 = m_request_id;
        if (result != null) {
            Bundle data = new Bundle();
            data.putByteArray("callbackkey", result);
            message.setData(data);
        }
        handler.sendMessage(message);

    }
}
